#include <main.h>

const uint8_t led_pins[8] = {PA1, PA2, PA3, PA4, PA5, PA6, PA7, PA8};

// 1为正向流动，-1为反向流动
int8_t led_flow_mode = 1;

#define BUTTON_PIN PB1

// #define BUTTON_RISING_FALLING
#define BUTTON_FALLING

void setup_led() {
    for (auto pin : led_pins) {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, HIGH);
    }
}

void loop_led() {
    const uint32_t cur_millis = millis();
    static uint32_t pre_millis = 0;
    const uint32_t period = 500;
    if (cur_millis - pre_millis >= period) {
        pre_millis = cur_millis;
        static uint8_t pre_i = 7;
        const uint8_t i = (pre_i + led_flow_mode + 8) % 8;

        digitalWrite(led_pins[pre_i], HIGH);
        digitalWrite(led_pins[i], LOW);

        pre_i = i;
    }
}

void setup_button() {
    pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop_button() {
    const uint32_t cur_millis = millis();
    static uint32_t pre_millis = 0;
    const uint32_t period = 20;
    if (cur_millis - pre_millis >= period) {
        pre_millis = cur_millis;
        
        auto is_pressed = []() -> bool {
            return digitalRead(BUTTON_PIN) ^ 1;
        };

        const bool cur_is_pressed = is_pressed();

        #if defined(BUTTON_RISING_FALLING)
            led_flow_mode = cur_is_pressed ? -1 : 1;
        #elif defined(BUTTON_FALLING)
            static bool pre_is_pressed = false;
            if (cur_is_pressed && !pre_is_pressed) {
                led_flow_mode = -led_flow_mode;
            }
            pre_is_pressed = cur_is_pressed;
        #endif

    }
}

void setup() {
    setup_led();
    setup_button();
}

void loop() {
    loop_led();
    loop_button();
}
